import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index'
const Login = () => import('@/views/login')
const Layout = () => import('@/views/layout')
const Search = () => import('@/views/search')
const SearchList = () => import('@/views/searchlist')
const ProDetail = () => import('@/views/prodetail')
const MyOrder = () => import('@/views/myorder')
const Pay = () => import('@/views/pay')

const Home = () => import('@/views/layout/home.vue')
const Category = () => import('@/views/layout/category.vue')
const Cart = () => import('@/views/layout/cart.vue')
const My = () => import('@/views/layout/my.vue')

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/layout',
    component: Layout,
    children: [
      {
        path: '/home',
        component: Home
      },
      {
        path: '/category',
        component: Category
      },
      {
        path: '/cart',
        component: Cart
      },
      {
        path: '/my',
        component: My
      }
    ]
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/searchList',
    component: SearchList
  },
  {
    path: '/proDetail/:goodsId?',
    component: ProDetail
  },
  {
    path: '/myOrder',
    component: MyOrder
  },
  {
    path: '/pay',
    component: Pay
  }
]

const router = new VueRouter({
  routes
})

const url = ['/myOrder', '/pay']

// 路由前置守卫
router.beforeEach((to, from, next) => {
  if (!url.includes(to.path)) {
    next()
    return
  }
  const token = store.getters.token
  console.log(token)
  if (token) {
    next()
  } else {
    next('/login')
  }
})
export default router
